﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
using YJYpublicClass;

namespace WindowsFormsApp2.Common
{
    public class TGQ_24V50 : ILightControl
    {
        private SerialPort sport = new SerialPort();

        private object syncRoot = new object();

        public bool Connection => sport.IsOpen;         //是否已连接
        public string Mes { get; set; }





        private TGQ_24V50_Config cft = new TGQ_24V50_Config();
        public ConfigBase cf
        {
            get { return cft; }
            set { cft = (TGQ_24V50_Config)value; }
        }
        public void Connect()
        {
            lock (syncRoot)
            {
                try
                {


                    if (sport.IsOpen)
                    {
                        sport.Close();
                    }
                    sport.PortName = "COM" + cft.port;
                    sport.BaudRate = cft.baudRate;
                    sport.StopBits = cft.stopBits;
                    sport.DataBits = cft.dataBits;
                    sport.ReadTimeout = cft.timeout;
                    sport.WriteTimeout = cft.timeout;
                    sport.Open();
                    sport.ReadExisting();
                }
                catch (Exception ex)
                {
                    string ex1 = ex.ToString();
                }
            }
        }



        public void Close()
        {
            lock (syncRoot)
            {
                sport.Close();
            }
        }
        public bool OpenChx(int chNo)
        {
            if (chNo == 0)
            {
                if (SetValue(0, cft.ch1SelV))
                {
                    return true;

                }
                else
                {
                    return false;

                }

            }
            else if (chNo == 1)
            {
                if (SetValue(1, cft.ch2SelV))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else if (chNo == 2)
            {
                if (SetValue(2, cft.ch3SelV))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else if (chNo == 3)
            {
                if (SetValue(3, cft.ch4SelV))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else
            {
                MessageBox.Show("光源通道号有误！");
                return false;

            }



        }
        public bool CloseChx(int chNo)
        {
            if (chNo == 0)
            {
                if (SetValue(0, 0))
                {
                    return true;

                }
                else
                {
                    return false;

                }

            }
            else if (chNo == 1)
            {
                if (SetValue(1, 0))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else if (chNo == 2)
            {
                if (SetValue(2, 0))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else if (chNo == 3)
            {
                if (SetValue(3, 0))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }
            else
            {
                MessageBox.Show("光源通道号有误！");
                return false;

            }

        }
        public bool OpenAll()
        {
            try
            {
                SetValue(0, cft.ch1SelV);
                SetValue(1, cft.ch2SelV);
                SetValue(2, cft.ch3SelV);
                SetValue(3, cft.ch4SelV);
                return true;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
                return false;
            }

        }
        public bool CloseAll()
        {
            try
            {
                SetValue(0, 0);
                SetValue(1, 0);
                SetValue(2, 0);
                SetValue(3, 0);
                return true;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
                return false;
            }

        }
        private bool SendChar(char ch)
        {
            sport.Write(new char[1] { ch }, 0, 1);
            char rch = (char)sport.ReadChar();
            return ch == rch;
        }

        private bool SendCommand(string cmd, out string ReCmd)
        {
            sport.WriteLine(cmd);
            Thread.Sleep(50);
            int n = sport.BytesToRead;
            Byte[] BUF = new byte[n];
            sport.Read(BUF, 0, n);
            ReCmd = System.Text.Encoding.UTF8.GetString(BUF);
            return true;
        }

        protected string ExecuteCommand(string cmd)
        {
            lock (syncRoot)
            {
                string Recmd = string.Empty;
                if (SendCommand(cmd, out Recmd))
                {
                    return Recmd.Trim().ToUpper();
                }
                return string.Empty;
            }
        }

        protected int GetIntegerValue(string cmd)
        {
            string ret = ExecuteCommand(cmd);
            return int.Parse(ret);
        }

        protected bool ExecuteAndCheckOk(string cmd)
        {
            string ret = ExecuteCommand(cmd);
            return ret.Equals("SUCCESS");
        }

        public int[] GetValue()
        {
            int[] vals = new int[8];
            string Cmd = "SA000TB000TC000TD000TR#";
            string ret = ExecuteCommand(Cmd);
            if (ret.IndexOf('#') > 0)
            {

                string[] retArr = ret.Split('T');
                vals[0] = int.Parse(retArr[0].Substring(2, 4));
                vals[1] = int.Parse(retArr[1].Substring(1, 4));
                vals[2] = int.Parse(retArr[2].Substring(1, 4));
                vals[3] = int.Parse(retArr[3].Substring(1, 4));
                
            }
            return vals;
        }

        public int GetValue(int chNo)
        {
            int[] vals = GetValue();
            if (chNo > 3)
            {
                return 0;
            }
            return vals[chNo];
        }

        /// <summary>
        /// 设置单通道值；通道号以0开始；值0-1000
        /// </summary>
        /// <param name="chNo"></param>通道号（0开头）
        /// <param name="val"></param>值
        /// <returns></returns>
        public bool SetValue(int chNo, int val)
        {

            byte[] btNumber = new byte[] { (byte)(chNo + 65) };
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            string ChChar = asciiEncoding.GetString(btNumber);
            string cmd = "S" + ChChar + val.ToString("000") + "TC#";
            return ExecuteAndCheckOk(cmd);
            //ExecuteAndCheckOk(cmd)多次封装
        }

        public bool SetValues(int[] channelArray, int[] values)
        {
            if (channelArray.Length != values.Length || channelArray.Length == 0 || values.Length == 0)
            {
                return false;
            }
            string cmd = "S";
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            for (int i = 0; i < channelArray.Length; i++)
            {
                byte[] btNumber = new byte[] { (byte)(channelArray[i] + 65) };
                string ChChar = asciiEncoding.GetString(btNumber);
                cmd += ChChar;
                cmd += values[i].ToString("000");
                cmd += "T";
            }
            cmd += "C#";
            return ExecuteAndCheckOk(cmd);
        }

        public bool IsExists()
        {
            if (!sport.IsOpen)
            {
                return false;
            }
            return true;
        }
    }



    public class TGQ_24V50_Config : ConfigBase
    {
        //[]中的为描述语句，表示参数的一些属性，用于在PropertyGrid中控制其显示特征
        [Category("串口参数"), Description("int类型"), DisplayName("COM口号"), ReadOnly(false)]
        //变量参数port等才是类的成员
        public int port { get; set; }
        [Category("串口参数"), Description("int类型"), DisplayName("波特率"), ReadOnly(false)]
        public int baudRate { get; set; }
        [Category("串口参数"), Description("int类型"), DisplayName("传输超时"), ReadOnly(false)]
        public int timeout { get; set; }
        [Category("串口参数"), Description("int类型"), DisplayName("停止位"), ReadOnly(false)]
        public StopBits stopBits { get; set; }
        [Category("串口参数"), Description("int类型"), DisplayName("数据位"), ReadOnly(false)]
        public int dataBits { get; set; }

        [Category("光源控制"), Description("int类型"), DisplayName("通道1值"), ReadOnly(false)]
        public int ch1SelV
        {
            get; set;
        }
        [Category("光源控制"), Description("int类型"), DisplayName("通道2值"), ReadOnly(false)]
        public int ch2SelV
        {
            get;
            set;
        }

        [Category("光源控制"), Description("int类型"), DisplayName("通道3值"), ReadOnly(false)]
        public int ch3SelV
        {
            get; set;
        }
        [Category("光源控制"), Description("int类型"), DisplayName("通道4值"), ReadOnly(false)]
        public int ch4SelV
        {
            get;
            set;
        }

        public TGQ_24V50_Config()
        {
            port = 1;
            baudRate = 115200;
            timeout = 2000;
            stopBits = StopBits.One;
            dataBits = 8;
            ch1SelV = 100;
            ch2SelV = 100;
            ch3SelV = 100;
            ch4SelV = 100;

            //记录4个通道值
        }
    }



}


